import { Component, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DValidateRules, DialogService, EditableTip, FormLayout, TableWidthConfig, TreeComponent } from 'ng-devui';
import { Part, ProcessDetail } from 'src/app/@core/data/MomData';
import { MomService } from 'src/app/@core/services/mom/mom.service';
import { ProcessService } from 'src/app/@core/services/process/process.service';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectTechnologyRouteComponent } from 'src/app/@shared/components/select-technology-route/select-technology-route.component';
import { PreViewmMomComponent } from '../pre-viewm-mom/pre-viewm-mom.component';
import { delay, of } from 'rxjs';

@Component({
  selector: 'app-edit-mom',
  templateUrl: './edit-mom.component.html',
  styleUrls: ['./edit-mom.component.scss']
})
export class EditMomComponent {
  @ViewChild('basicTree', { static: true }) basicTree: TreeComponent;
  msgs: { severity: any; summary: any; content: any; }[];
  tabActiveId: string | number = '工序';
  value1 =[]
  layoutDirection: FormLayout = FormLayout.Horizontal;
  originalProcessNumber:any
  originalPartNumber:any
  data = [
  ];
  MaterialData=[
    {
      number:1,
      code:null,
      name:null,
      consumption:null,
      loss:null
    }
  ];
  nodes =[];
  Parts=[
      {
        partId: null,
        partNum: "",
        partName: "",
        partNumber: null,
        unitUsage: 0,
        lossRate: 0,
        fixedLoss: 0,
        partType: '',
        partUOM: '',
        fixedLossDisabled: false,
        lossRateDisabled: false,
      }
  ]
  ProcessDetails:ProcessDetail[]=[
    {
      processId: null,
      processNum: "",
      processName: "",
      processNumber: null,
      isFirstInspection: true,
      isOutsourcing: true,
      unitTime:null,
      isInspection: true,
      parts: this.Parts
    }
  ]
  processNumberRule:boolean = false;
  Materials:Part[]=[]
  selectNode = this.nodes[0];
  MomData={
    partId: null,
    partNum: "",
    partName: "",
    version: "",
    technologyRouteId: null,
    technologyRouteNum: "",
    technologyRouteName: "",
    startDate: "",
    endDate: "",
    isApproval: false,
    momProcesses: this.ProcessDetails,
    Materials:this.Materials
  };
  MOM={
    partId: null,
    partNum: "",
    partName: "",
    version: "",
    technologyRouteId: null,
    technologyRouteNum: "",
    technologyRouteName: "",
    startDate: "",
    endDate: "",
    isApproval: false,
    momProcesses: []
  }
  display = false;
  options =[];
  processOptions:[]
  isClicked = false;
  nameEditing: boolean;
  treeData :any
  editableTip = EditableTip.btn
  devuiTableWidthConfig: TableWidthConfig[] = [
    {
      field: 'number',
      width: '150px',
    },
    {
      field: 'number',
      width: '150px',
    },
    {
      field: 'number',
      width: '150px'
    },
    {
      field: 'code',
      width: '150px'
    },
    {
      field:'name',
      width:'150px'
    },
    {
      field: 'consumption',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
    {
      field: 'loss',
      width: '150px'
    },
  ]//表格宽度配置
  momFormRules:{[key:string]:DValidateRules} = {
    partNum:{
      messageShowType:'text',
      validators:[
        {required:true,message:'物料编码不能为空'}
      ]
    },
    partName:{
      messageShowType:'text',
      validators:[
        {required:true,message:'物料名称不能为空'}
      ]
    },
    version:{
      messageShowType:'text',
      validators:[
        {required:true,message:'版本不能为空'},
        { pattern: /^[^\s]*$/, message: '*工序编码不能包含空格' }
      ]
    },
    technologyRouteNum:{
      messageShowType:'text',
      validators:[
      ]
    },
    technologyRouteName:{
      messageShowType:'text',
      validators:[
      ]
    },
    startDate:{
      messageShowType:'text',
      validators:[
        {required:true,message:'有效期不能为空'},
        { requiredTrue: this.value1.length==2, message: '*有效期不能为空' }
      ]
    },
    endDate:{
      messageShowType:'text',
      validators:[
        {required:true,message:'有效期不能为空'},
        { requiredTrue: this.value1.length==2, message: '*有效期不能为空' }
      ]
    },
    unitTime:{
      messageShowType:'text',
      validators:[
        {required:true,message:'单位工时不能为空'},
        { pattern: /^(0\.\d+|[1-9]\d*(\.\d+)?)$/, message: '*工时必须为正数且不能为0' }]
    },
    processNumber:{
      messageShowType:'text',
      validators:[
        {required:true,message:'*工序序号不能为空'},
        {pattern:/^[1-9]\d*$/,message:"*工序序号不可为0或负数"}
      ],
      asyncValidators:[
        { sameNumber: this.processNumber.bind(this), message: {
            'zh-cn': '*工序序号'+'重复',
          }
        }
      ]
    },
  }
  gongxuArea ={
    min:1,
    max:Number.MAX_VALUE
  }
  MatrialArea ={
    min:1,
    max:Number.MAX_VALUE
  }
  MatrialIndex = 0;
  maxHeight = 'calc(100vh - 570px)'
  selectNodeIndex: any;
  momId: any;
  constructor(private dialogService:DialogService,private ProcessService:ProcessService,private MomService:MomService,private Router:Router,private ActivatedRoute:ActivatedRoute){}
  ngOnInit(): void {
    this.ProcessService.GetPagedProcesss(null,1,999).subscribe((res:any)=>{
      this.processOptions = res.items
    })
    this.ActivatedRoute.params.subscribe((params:any)=>{
      const id = params['momId'];
      this.momId = id;
      this.MomService.GetMOMById(id).subscribe((res:any)=>{
        this.MomData = res;
        this.MomData.momProcesses.forEach((node: { parts: any[]; }) => {
          node.parts.map((part:any) => {
           if(part.lossRate>0){
              part.fixedLossDisabled = true;
              part.lossRateDisabled = false;
           }else{
              part.fixedLossDisabled = false;
              part.lossRateDisabled = true;
           }
          });
        });
        this.MomData.partId = res.productionId;
        this.value1 = [new Date(res.startDate),new Date(res.endDate)];
        const allParts = [].concat(...this.MomData.momProcesses.map(process => process.parts));
        this.Materials = allParts;
        this.MomData.Materials = this.Materials;
        this.treeData = this.transformData(this.MomData);
        this.nodes = res.momProcesses;
      })
    })
  }
  SelectMaterial(dialogtype?: string,){
    let data ={
      display: false,
      placeholder: '请选择物料'
    }
    const results = this.dialogService.open({
      id: 'department',
      width: '1000px',
      maxHeight: '800px',
      title: '物料',
      data:data,
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.MomData.partId = results.modalContentInstance.selectData.partId;
              this.MomData.partNum = results.modalContentInstance.selectData.partNum;
              this.MomData.partName = results.modalContentInstance.selectData.partName;
              this.MomData.Materials = this.Materials;
              if(this.MomData.momProcesses[0].processNumber==null){
                this.MomData.momProcesses = [];
              }
              results.modalInstance.hide();
              this.treeData = this.transformData(this.MomData);

            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  SelectTechnologyRoute(dialogtype?: string,){
    let data ={
      display: false,
      placeholder: '请选择工艺路线'
    }
    const results = this.dialogService.open({
      id: 'department',
      width: '700px',
      maxHeight: '800px',
      title: '工艺路线',
      data:data,
      content: SelectTechnologyRouteComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.MomData.technologyRouteId = results.modalContentInstance.selectData.technologyRouteId;
              this.MomData.technologyRouteNum = results.modalContentInstance.selectData.technologyRouteNum;
              this.MomData.technologyRouteName = results.modalContentInstance.selectData.technologyRouteName;
              this.ProcessService.GetTechnologyRouteById(results.modalContentInstance.selectData.technologyRouteId).subscribe((res: any) => {
                this.MomData.momProcesses = res.processDetails.map((node: any) => ({ ...node, parts: [], isInspection: true, unitTime: 0, }));
                this.nodes = res.processDetails.map((node: any) => ({
                  ...node, parts: [], isInspection: true,
                  unitTime: 0,
                }));

                this.treeData = this.transformData(this.MomData);
              })
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  versionChange($event?:any){
    this.treeData = this.transformData(this.MomData);
  }
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  onChange($event: any){
    this.MomData.startDate = $event[0]
    this.MomData.endDate =$event[1]
  }
  addNode(node?: any, index?: any, nextNode?: any) {
    if (this.MomData.technologyRouteNum) {
      if (node) {
        if (nextNode) {
          if (nextNode.processNumber - node.processNumber > 1) {
            const newNode = { processNumber: Math.round((node.processNumber + nextNode.processNumber) / 2), isFirstInspection: false, processId: null, processName: '未设置工序', isLastInspection: false, processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false };
            const index = this.nodes.indexOf(node);
            this.nodes.splice(index + 1, 0, newNode);
            this.MomData.momProcesses = this.nodes.map((node, index) => {
              return {
                ...node,
              };
            })
            this.treeData = this.transformData(this.MomData);
          } else {
            this.showToast('error', '错误', '序号' + node.processNumber + '和序号' + nextNode.processNumber + '中不能添加工序')
          }
        } else {
          const newNode = { processNumber: node.processNumber + 10, isFirstInspection: false, processId: null, processName: '未设置工序', isLastInspection: false, processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false };
          this.nodes.splice(index + 1, 0, newNode);
          this.MomData.momProcesses = this.nodes.map((node, index) => {
            return {
              ...node,
            };
          })
        }
      } else {
        if (!this.nodes[0]?.processNumber) {
          const newNode = { processNumber: 10, isFirstInspection: false, processId: null, processName: '未设置工序', isLastInspection: false, processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false };
          this.nodes.unshift(newNode);
          this.MomData.momProcesses = this.nodes.map((node, index) => {
            return {
              ...node,
            };
          })
          this.treeData = this.transformData(this.MomData);
        }
        else if (this.nodes[0].processNumber) {
          if (this.nodes[0].processNumber > 1) {
            const newNode = { processNumber: Math.round(this.nodes[0].processNumber / 2), isFirstInspection: false, processId: null, processName: '未设置工序', isLastInspection: false, processNum: null, isOutsourcing: false, parts: [], unitTime: 0, isInspection: false };
            this.nodes.unshift(newNode);
            this.MomData.momProcesses = this.nodes.map((node, index) => {
              return {
                ...node,
              };
            })
            this.treeData = this.transformData(this.MomData);
          } else {
            this.showToast('error', '错误', '序号不能小于1')
          }
        }
      }
    }
    else {
      this.showToast('error', '错误', '请先选择工艺路线！');
    }
  }
  deleteNode(node?:any,){
    this.Materials = this.Materials.filter(material => !node.parts.some((part: { partNumber: number; }) => part.partNumber === material.partNumber));
    this.nodes = this.nodes.filter(item=>item.processNumber!==node.processNumber)
    this.display = false;
    this.MomData.momProcesses = this.nodes.map((node, index) => {
      return {
        ...node,
      };
    })
    this.MomData.Materials = this.Materials;
    this.treeData = this.transformData(this.MomData);
  }
  editNode(node:any,last:any,next:any,i?:any){
    if(!this.processNumberRule){
    this.display = true;
    this.selectNode = node;
    this.originalProcessNumber = node.processNumber;
    this.selectNodeIndex = i;
    this.nodes.forEach(node => {
      node.isClicked = false;
    });
    this.selectNode.isClicked = true;

    }else{
      this.showToast('error', '错误', '请先填写正确的工序号');
    }

  }
  saveNode(){
  }
  selectGroup($event:any){
  }
  editProcessNumber($event:any){
    let hasDuplicates = this.nodes.filter((node, index, self) =>
    index !== self.findIndex((t) => (t.processNumber === node.processNumber))
    ).length > 0;
    if (hasDuplicates){
      this.showToast('error', '错误', '已有相同工序号');
      this.selectNode.processNumber = this.originalProcessNumber;
      this.processNumberRule = true;
      this.nodes.sort((a, b) => a.processNumber - b.processNumber);
      this.nodes.sort((a, b) => {
        if (a.processNumber == null) return 1;
        if (b.processNumber == null) return -1;
        return a.processNumber - b.processNumber;

      });
      this.MomData.momProcesses = this.nodes.map((node, index) => {
        return {
          ...node,
        };
      })
      this.treeData = this.transformData(this.MomData);
    }else{
      this.processNumberRule = false;
      this.selectNode.processNumber = $event;
      this.originalProcessNumber = $event;
      this.nodes.sort((a, b) => a.processNumber - b.processNumber);
        this.MomData.momProcesses = this.nodes.map((node, index) => {
          return {
            ...node,
          };
        })
      this.treeData = this.transformData(this.MomData);
    }
  }
  selectProcess($event: any){
    this.selectNode.processId = $event.processId
    this.selectNode.processName = $event.processName
    this.selectNode.processNum = $event.processNum
    this.MomData.momProcesses = this.nodes.map((node, index) => {
      return {
        ...node,
      };
    })
    this.treeData = this.transformData(this.MomData);

  }
  addMaterial($event?:any,index?:any,nextPart?:any){
    const maxMaterialNumber =  this.getMaxMaterialNumberBeforeCurrentProcess(this.selectNode);
    const minMaterialNumber = this.getMinMaterialNumberAfterCurrentProcess(this.selectNode);
    if(!$event){
      if(maxMaterialNumber === null && minMaterialNumber === null){
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: ''
        });
      } else if(maxMaterialNumber && minMaterialNumber === null){
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: maxMaterialNumber + 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: ''
        });
      } else if(maxMaterialNumber === null && minMaterialNumber){
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: minMaterialNumber - 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: ''
        });
      }else if(maxMaterialNumber&&minMaterialNumber){
        if(minMaterialNumber-maxMaterialNumber>1){
          this.selectNode.parts.push({
            partId: null,
            partNum: "",
            partName: "",
            partNumber: Math.round((maxMaterialNumber + minMaterialNumber) / 2),
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: ''
          });
        }else{
          this.showToast('error','错误','物料号'+maxMaterialNumber+'和物料号'+minMaterialNumber+'之间不能添加物料')
        }
      }
       else {
        this.selectNode.parts.push({
          partId: null,
          partNum: "",
          partName: "",
          partNumber: 10,
          unitUsage: 1,
          lossRate: 0,
          fixedLoss: 0,
          partType: '',
          partUOM: ''
        });
      }
    }else{
      if(nextPart){
        if(nextPart.partNumber-$event.partNumber>1){
          this.selectNode.parts.splice(index + 1, 0, {
            partId: null,
            partNum: "",
            partName: "",
            partNumber: Math.round(($event.partNumber + nextPart.partNumber) / 2),
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: ''
          })
        }else{
          this.showToast('error','错误','物料号'+$event.partNumber+'和物料号'+nextPart.partNumber+'之间不能添加物料')
        }
      }else{
        if(minMaterialNumber){
          if((minMaterialNumber-$event.partNumber)>1){
            this.selectNode.parts.push({
              partId: null,
              partNum: "",
              partName: "",
              partNumber: Math.round((minMaterialNumber +$event.partNumber)/2),
              unitUsage: 1,
              lossRate: 0,
              fixedLoss: 0,
              partType: '',
              partUOM: ''
            });
          }else{
            this.showToast('error','错误','物料号'+$event.partNumber+'和物料号'+minMaterialNumber+'之间不能添加物料')
          }
        }else{
          this.selectNode.parts.push({
            partId: null,
            partNum: "",
            partName: "",
            partNumber: $event.partNumber+10,
            unitUsage: 1,
            lossRate: 0,
            fixedLoss: 0,
            partType: '',
            partUOM: ''
          });

        }
      }
    }
    this.Materials = this.nodes.reduce((materials, process) => {
      return materials.concat(process.parts);
    }, []).sort((a: { partNumber: number; }, b: { partNumber: number; }) => a.partNumber - b.partNumber);
    this.MomData.Materials = this.Materials;
    this.MomData.momProcesses = this.nodes
    this.treeData  = this.transformData(this.MomData)
  }
  getMaxMaterialNumberBeforeCurrentProcess(selectNode:any): number {
    // 假设你的所有工序存储在一个名为this.processes的数组中
    let maxMaterialNumber = -Infinity;// 用于存储最大的物料序号
    for (let i = 0; i < this.nodes.length; i++) {
      let process = this.nodes[i];
      if (process === selectNode) {
        break;
      }
      if (process.parts && process.parts.length > 0) {
        // 获取这个工序的最大物料序号
        let maxNumberInProcess = Math.max(...process.parts.map((material: { partNumber: any; }) => material.partNumber));
        maxMaterialNumber = Math.max(maxMaterialNumber, maxNumberInProcess);
      }
    }
    // 如果没有找到任何有物料的工序，返回10作为默认的物料序号
    return maxMaterialNumber === -Infinity ? null : maxMaterialNumber;
  }
  getMinMaterialNumberAfterCurrentProcess(selectNode:any): number {
    // 假设你的所有工序存储在一个名为this.processes的数组中
    let minMaterialNumber = Infinity;
    let foundCurrentProcess = false;
    for (let i = 0; i < this.nodes.length; i++) {
      let process = this.nodes[i];
      if (process === selectNode) {
        foundCurrentProcess = true;
        continue;
      }
      if (foundCurrentProcess && process.parts && process.parts.length > 0) {
        // 获取这个工序的最小物料序号
        let minNumberInProcess = Math.min(...process.parts.map((material: { partNumber: any; }) => material.partNumber));
        minMaterialNumber = Math.min(minMaterialNumber, minNumberInProcess);
      }
    }
    // 如果没有找到任何有物料的工序，返回10作为默认的物料序号
    return minMaterialNumber === Infinity ? null : minMaterialNumber;
  }
  processNumberChange(){
    this.nodes.sort((a, b) => a.processNumber - b.processNumber);
    this.MomData.momProcesses = this.nodes.map((node, index) => {
      return {
        ...node,
      };
    })
    this.treeData = this.transformData(this.MomData);
  }
  processNumber(value:any){
    let res = true;
    let processNumbers = this.MomData.momProcesses.map(process => process.processNumber);
    let duplicates = processNumbers.filter((item, index) => processNumbers.indexOf(item) != index);

    if (duplicates.length > 0) {
        res = false;
       }
    return of(res).pipe(delay(100));
  }
  editingChange(rowItem:any){
    let Index = this.Materials.findIndex(item => item.partNumber === rowItem.partNumber);
    this.MatrialIndex = Index;
    this.originalPartNumber = rowItem.partNumber;
  }
  removeMaterial(i: number,partNumber:any){
    this.selectNode.parts.splice(i,1);
    this.Materials = this.Materials.filter(material => material.partNumber !== partNumber);
    this.MomData.Materials = this.Materials;
    this.MomData.momProcesses[this.selectNodeIndex].parts = this.selectNode.parts;
    this.treeData = this.transformData(this.MomData);
  }
  SelectMaterials(index:number,partNumber?:any,dialogtype?: string,){
    let data = {
      display: false,
      placeholder: '请选择物料'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '1000px',
      title: '物料',
      data:data,
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              if(this.MaterialData.some(item => item.code === results.modalContentInstance.selectData.partId)){
                this.showToast('error', '错误', '不能重复选择物料');
              }else{
                this.selectNode.parts[index].partId = results.modalContentInstance.selectData.partId;
                this.selectNode.parts[index].partNum = results.modalContentInstance.selectData.partNum;
                this.selectNode.parts[index].partName = results.modalContentInstance.selectData.partName;
                this.selectNode.parts[index].partType = results.modalContentInstance.selectData.partType;
                this.selectNode.parts[index].partUOM = results.modalContentInstance.selectData.partUOM;
                this.selectNode.parts[index].unitUsage = 1;
                this.selectNode.parts[index].lossRate = 0;
                this.selectNode.parts[index].fixedLoss = 0;
                delete this.selectNode.parts[index].codeEdit;
                let Material = this.Materials.find(Material => Material.partNumber === partNumber);
                Material.partId = results.modalContentInstance.selectData.partId;
                Material.partNum = results.modalContentInstance.selectData.partNum;
                Material.partName = results.modalContentInstance.selectData.partName;
                Material.unitUsage = 1;
                Material.lossRate = 0;
                this.MomData.Materials = this.Materials;
                this.MomData.momProcesses[this.selectNodeIndex].parts = this.selectNode.parts;
                this.treeData = this.transformData(this.MomData);

              }
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//物料物料
  partNumberRule:boolean = false;
  partNumberChange($event:any,rowIndex?:any){
    if(this.Materials.some(item => item.partNumber === $event)){
      this.showToast('error', '错误', '已有相同物料号');
      this.selectNode.parts[rowIndex].partNumber = this.originalPartNumber;
      this.Materials[this.MatrialIndex].partNumber = this.originalPartNumber;
    }else{
      this.Materials[this.MatrialIndex].partNumber = $event;
      this.Materials.sort((a, b) => a.partNumber - b.partNumber);
      this.selectNode.parts.sort((a: { partNumber: number; }, b: { partNumber: number; }) => a.partNumber - b.partNumber);
      this.MomData.Materials = this.Materials;
      this.MomData.momProcesses[this.selectNodeIndex].parts = this.selectNode.parts;
      this.treeData = this.transformData(this.MomData);
    }

  }
  submit(){
    this.ProcessDetails = this.nodes.map(({ isClicked, ...rest }) => rest)
    this.ProcessDetails = this.ProcessDetails.map((node, index) => {
      return {
        ...node,
        processNumber: node.processNumber,
          parts: node.parts,
      };
    });
    this.MomData.momProcesses = this.ProcessDetails;
    this.MomData = { ...this.MomData };
    delete this.MomData.Materials;
    let momData = {
      partId: this.MomData.partId,
      partNum: this.MomData.partNum,
      partName: this.MomData.partName,
      version: this.MomData.version,
      technologyRouteId: this.MomData.technologyRouteId,
      technologyRouteNum: this.MomData.technologyRouteNum,
      technologyRouteName: this.MomData.technologyRouteName,
      startDate: this.MomData.startDate,
      endDate: this.MomData.endDate,
      isApproval: this.MomData.isApproval,
      momProcesses: this.MomData.momProcesses,
    }
    const includeKeys = ['partNum', 'partName', 'version', 'technologyRouteNum', 'technologyRouteName', 'startDate', 'endDate', 'momProcesses','unitTime','unitUsage', 'partNumber', 'processName', 'processNum', 'processNumber'];
      const keyMap = {
        'partNum': '物料编码',
        'partName': '物料名称',
        'version': '版本',
        'technologyRouteId': '工艺路线ID',
        'technologyRouteNum': '工艺路线编码',
        'technologyRouteName': '工艺路线名称',
        'startDate': '开始日期',
        'endDate': '结束日期',
        'processId': '工序ID',
        'processName': '工序名称',
        'processNum': '工序编码',
        'processNumber': '工序序号',
        'unitTime': '单位工时',
        'partId': '物料ID',
        'partNumber': '物料序号',
        'unitUsage': '单位用量'
    };
    const errors = this.checkEmptyProperties(momData, '', includeKeys, keyMap);
    if(errors.length > 0){
      this.showToast('wran','错误',errors[0])
    }
    if (errors.length === 0) {
      this.MomService.UpdateMOM(this.momId,momData).subscribe(
        (res:any)=>{
        this.showToast('success','成功','更新成功')
        setTimeout(() => {
          this.Router.navigate(['/pages/process/mom'])
        },1000)
        },
        (error) => {
          if(error.status==404){
            this.showToast('error', '失败', '服务器连接失败');
          }else{
            this.showToast('error', '失败', error.error);
          }
        }
        )
    }
  }
  iconLeaf = '<span></span>';
  transformData(data: any) {
    return [{
      title:data.partName+" 版本："+data.version,
      open: true,
      treeId: "mom",
      icon:{icon:'icon-unarchived-item'},
      showCheckbox: false,
      disableDelete: true,
      items:[
        {
          title:'工序',
          open: true,
          treeId: "process",
          icon:{icon:'icon-merge-request2'},
          showCheckbox: false,
          disableDelete: true,

          items:data.momProcesses.map((detail: { processNumber:any,processName: any; processId: any; parts: any[]; }) => ({
            title: "工序"+detail.processNumber+"： "+detail.processName,
            data: detail,
            open: true,
            showCheckbox: false,
            disableDelete: true,
            icon:{icon:'icon-tag'},
            items:detail.parts.map(part => ({
              title: "物料"+part.partNumber+"： "+part.partName,
              data: part,
              showCheckbox: false,
              disableDelete: true,
              icon:{icon:''},
            }))
          }))
        },{
          title:"物料",
          open: true,
          treeId: "process",
          showCheckbox: false,
          disableDelete: true,
          icon:{icon:'B'},
          items:data.Materials.map((material: {partNumber:any; partName: any; partId: any; }) => ({
            title:"物料"+material.partNumber+"： "+ material.partName,
            data: material,
            showCheckbox: false,
            disableDelete: true,
            icon:{icon:''},
          }))
        }
      ]
    }];
  }
  cancle(){
    this.Router.navigate(['/pages/process/mom'])
  }
  preview(dialogtype?:string){
    const results = this.dialogService.open({
      width:'1000px',
      title: 'MOM预览',
      backdropCloseable:false,
      data:{
        nodes:this.nodes
      },
      content: PreViewmMomComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  lossRateChange($event:any,rowItem:any){
    rowItem.lossRate = $event/100
      if($event>0){
        rowItem.fixedLossDisabled = true;
      }else{
        rowItem.fixedLossDisabled = false;
      }
  }
  fixedLossChange($event:any,rowItem:any){
      if($event>0){
        rowItem.lossRateDisabled = true;
      }else{
        rowItem.lossRateDisabled = false;
      }
  }
  checkEmptyProperties(obj: any, parentKey = '', includeKeys = [], keyMap = {}) {
      let emptyProperties = [];
      for (let key in obj) {
          // 如果当前属性不在包含列表中，跳过检查
          if (!includeKeys.includes(key)) {
              continue;
          }
          let fullKey = parentKey ? `${parentKey}.${key}` : key;
          let mappedKey = keyMap[key] || key; // 使用映射对象获取属性的中文名，如果没有映射，就使用原名
          if (obj[key] && typeof obj[key] === 'object') {
              if (Array.isArray(obj[key]) && key === 'momProcesses') {
                console.log(obj[key])
                  obj[key].forEach((item, index) => {
                      let processName = item.processName || '';
                      let processNumber = item.processNumber || '';
                      let childKey = `工序${processNumber}:${processName}`; // 添加'工序'、工序的索引和工序的名称
                      emptyProperties = emptyProperties.concat(this.checkEmptyProperties(item, childKey, includeKeys, keyMap));

                      // 如果工序下存在物料，遍历物料并检查物料的属性
                      if (item.parts) {
                          item.parts.forEach((material, materialIndex) => {
                              let materialName = material.partName || '';
                              let materialNumber = material.partNumber || '';
                              let materialKey = `${childKey}的物料${materialNumber}${materialName}`; // 添加'物料'、物料的索引和物料的名称
                              emptyProperties = emptyProperties.concat(this.checkEmptyProperties(material, materialKey, includeKeys, keyMap));
                          });
                      }
                  });
              } else {
                  emptyProperties = emptyProperties.concat(this.checkEmptyProperties(obj[key], fullKey, includeKeys, keyMap));
              }
          } else if (obj[key] === undefined || obj[key] === null || obj[key] === '' || (typeof obj[key] === 'number' && obj[key] <= 0 && includeKeys.includes(key))) {
            let errorKey = parentKey ? `${parentKey}.${mappedKey}` : mappedKey;
            errorKey = errorKey.replace('momProcesses.', '').replace(/\./g, '的'); // 在生成错误信息时，移除'momProcesses.'，并将'.'替换为'的'
            emptyProperties.push(errorKey + ' 不能为空');
        } else if (typeof obj[key] === 'number' && obj[key] <= 0 && !includeKeys.includes(key)) {
            let errorKey = parentKey ? `${parentKey}.${mappedKey}` : mappedKey;
            errorKey = errorKey.replace('momProcesses.', '').replace(/\./g, '的'); // 在生成错误信息时，移除'momProcesses.'，并将'.'替换为'的'
            emptyProperties.push(errorKey + ' 不能小于等于0');
        }
      }
      return emptyProperties;
  }
}
